/***************************************************************************

-------------------
    begin                : 
    copyright            : kuzkok
    email                : kuzkok at gmail.com

***************************************************************************
*                                                                         *
*   This program is free software; you can redistribute it and/or modify  *
*   it under the terms of the GNU General Public License as published by  *
*   the Free Software Foundation; either version 2 of the License, or     *
*   (at your option) any later version.                                   *
*   
*   Данная программа является свободным программным обеспечением;         *
*   Вы можете распространять ее и/или модифицировать в соответствии с     *
*   GNU General Public License опубликованной Фондом свободного           *
*   программного обеспечения; используемая версия лицензии - 2 или        *
*   (по вашему выбору) любая более поздняя                                *
***************************************************************************/
#include <QMessageBox>

#include "apdmobject.h"
#include "dbconnection.h"


APDMObject::APDMObject(QString theTableName)
{    
    mTableName = theTableName;
    mEventID = QUuid::createUuid();
    mObjectState = OSNew;
}

APDMObject::APDMObject(QUuid theEventID, QString theTableName)
{
    mTableName = theTableName;
    mEventID = theEventID;
    mSelectQuery = new QSqlQuery(dbconnection::instance()->database());
    mSelectQuery->prepare("select * from "+mTableName+" where eventid=:id");
    mSelectQuery->bindValue(":id", mEventID.toString());
    if(mSelectQuery->exec() && mSelectQuery->next())
    {
        mObjectState = OSOld;
    }
    else
    {
        mObjectState = OSInvalid;
    }
}

APDMObject::APDMObject(QString theTableName, QString whereclause)
{
    mTableName = theTableName;
    mSelectQuery = new QSqlQuery(dbconnection::instance()->database());
    mSelectQuery->prepare("select * from "+mTableName+" where "+whereclause);
    if(mSelectQuery->exec() && mSelectQuery->next())
    {
        mObjectState = OSOld;
        mEventID = QUuid(mSelectQuery->value(mSelectQuery->record().indexOf("eventid")).toString());
    }
    else
    {
        mObjectState = OSInvalid;
    }
}

APDMObject::~APDMObject()
{
    delete mSelectQuery;
}

bool APDMObject::deleteObject()
{
    if(mObjectState == OSNew) return false;
    QSqlQuery query(dbconnection::instance()->database());
    query.prepare("delete from "+mTableName+" where eventid=:id");
    query.bindValue(":id", UuidToVariant(mEventID));
    if(!query.exec())
    {
        QMessageBox::information(0,
                                 "Ошибка удаления",
                                 query.lastError().text());
        return false;
    }
    mObjectState = OSInvalid;
    return true;
}

bool APDMObject::saveObject()
{
    QString queryString = "";
    switch(mObjectState)
    {
    case OSNew:
        buildInsertStatement();
        queryString = "insert into "+mTableName;
        queryString += "("+mInsertStatementFields+")";
        queryString += "values ("+mInsertStatementValues+")";
        break;
    case OSOld:
        buildUpdateStatement();
        queryString = "update "+mTableName+" set ";
        queryString += mUpdateStatement;
        queryString += " where eventid=:eventid";
        break;
    case OSInvalid:
        return false;
        break;
    }
    QSqlQuery query(dbconnection::instance()->database());
    query.prepare(queryString);
    bindQueryValues(query);
    if(!query.exec())
    {
        QMessageBox::information(0,
                                 "Ошибка сохранения",
                                 query.lastError().text());
        return false;
    }
    return true;
}

void APDMObject::buildUpdateStatement()
{
    mUpdateStatement = "";
}

void APDMObject::buildInsertStatement()
{
    mInsertStatementFields = "eventid";
    mInsertStatementValues = ":eventid";
}

void APDMObject::bindQueryValues(QSqlQuery &query)
{
    query.bindValue(":eventid", UuidToVariant(mEventID));
}

QUuid APDMObject::findObjectID(QString field, QVariant value)
{
    QSqlQuery query(dbconnection::instance()->database());
    query.prepare("select * from "+mTableName+" where "+field+" =:fval");
    query.bindValue(":fval", value);
    if(query.exec() && query.next())
    {
        return QUuid(query.value(query.record().indexOf("eventid")).toString());
    }
    return QUuid();
}
